package com.xm.ojcodesandbox;

import cn.hutool.core.util.ArrayUtil;
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.async.ResultCallback;
import com.github.dockerjava.api.command.*;
import com.github.dockerjava.api.model.*;
import com.github.dockerjava.core.DockerClientBuilder;
import com.xm.ojcodesandbox.model.ExecuteMessage;
import org.springframework.stereotype.Component;

import java.io.Closeable;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
@Component
public class JavaDockerSandbox extends JavaCodeSandboxTemplate {

    private static final boolean FIRST_INIT = true;
    @Override
    public List<ExecuteMessage> execCode(File userCodeFile, List<String> inputList) {
        //3 创建容器，把文件复制到容器内
        String userCodeParentFilePath = userCodeFile.getParentFile().getAbsolutePath();
        DockerClient dockerClient = DockerClientBuilder.getInstance().build();
        String image = "openjdk:8-alpine";

        //3.1拉取镜像
        if (FIRST_INIT) {
            PullImageCmd pullImageCmd = dockerClient.pullImageCmd(image);
            PullImageResultCallback pullImageResultCallback = new PullImageResultCallback() {
                @Override
                public void onNext(PullResponseItem item) {
                    System.out.println("下载镜像: " + item.getStatus());
                    super.onNext(item);
                }
            };
            try {
                pullImageCmd.exec(pullImageResultCallback).awaitCompletion();
            } catch (InterruptedException e) {
                System.out.println("拉取镜像异常");
                throw new RuntimeException(e);
            }
        }
        //3.2 创建容器
        CreateContainerCmd containerCmd = dockerClient.createContainerCmd(image);
        HostConfig hostConfig = HostConfig.newHostConfig();
        hostConfig.setBinds(new Bind(userCodeParentFilePath, new Volume("/app")));
        CreateContainerResponse containerResponse = containerCmd
                .withNetworkDisabled(true) //网络安全
                .withMemory(100 * 1024 * 1024L)//内存限制
                .withHostConfig(hostConfig)
                .withAttachStdin(true)
                .withAttachStderr(true)
                .withAttachStdout(true)
                .withTty(true)
                .exec();
        //需要维护一个执行信息， 内存 、 时间等 StopWatch统计时间
        List<ExecuteMessage> executeMessage = new ArrayList<ExecuteMessage>(); //TODO
        String containerId = containerResponse.getId();
        for (String inputArgs : inputList) {
            String[] inputArgsArray = inputArgs.split(" ");
            String[] cmdArray = ArrayUtil.append(new String[]{"java", "-cp", "/app", "Main"}, inputArgsArray);
            ExecCreateCmdResponse execCreateCmdResponse = dockerClient.execCreateCmd(containerId)
                    .withCmd(cmdArray)
                    .withAttachStderr(true)
                    .withAttachStdin(true)
                    .withAttachStdout(true)
                    .exec();
            String execId = execCreateCmdResponse.getId();
            //没有这个实现类
//            ExecStartResultCallback execStartResultCallback = new ExecStartResultCallback() {
//                @Override
//                public void onNext(Frame frame) {
//                    StreamType streamType = frame.getStreamType();
//                    if (StreamType.STDERR.equals(streamType)) {
//                        System.out.println("输出错误结果：" + new String(frame.getPayload()));
//                    } else {
//                        System.out.println("输出结果：" + new String(frame.getPayload()));
//                    }
//                    super.onNext(frame);
//                }
//            };
//            try {
//                dockerClient.execStartCmd(execId)
//                  .exec(execStartResultCallback)
//                  .awaitCompletion(TIME_OUT, TimeUnit.MICROSECONDS);
//            } catch (InterruptedException e) {
//                System.out.println("程序执行异常");
//                throw new RuntimeException(e);
//            }
            // 获取占用的内存
            StatsCmd statsCmd = dockerClient.statsCmd(containerId);
            ResultCallback<Statistics> statisticsResultCallback = statsCmd.exec(new ResultCallback<Statistics>() {
                long[] maxMemory = {0L};
                @Override
                public void onNext(Statistics statistics) {
                    System.out.println("内存占用：" + statistics.getMemoryStats().getUsage());
                    maxMemory[0] = Math.max(statistics.getMemoryStats().getUsage(), maxMemory[0]);
                }
                @Override
                public void close() throws IOException {
                }
                @Override
                public void onStart(Closeable closeable) {
                }
                @Override
                public void onError(Throwable throwable) {
                }
                @Override
                public void onComplete() {

                }
            });

            statsCmd.exec(statisticsResultCallback);

        }
        return executeMessage;
    }

}